<!--监听播放器 -->
<template>
  <div>
    <Modal  v-model="modal.show"  :title="modal.title"  :mask-closable="false" :footer-hide=true
            width="400px"  :closable="false" >
      <Row v-show="loading">
        <Col span="24">
           <div style="width: 100%;height: 190px;display: flex;
              justify-content: center;align-items: center;background-color: #00060c" >
             <Spin size="large" ></Spin>
           </div>
        </Col>
      </Row>
      <Row v-show="!loading">
        <Col span="24">
          <div style="width: 100%;height: 100%; background-color: #00060c" >
            <audio  v-show="1===0" id="audioPlayer1"  ref="audioPlayer1"  class="audioPlayerJt" autoplay controls />
            <canvas id="audioCanvas" ref="audioCanvas" style="width: 100%;height: 100%"></canvas>
          </div>

        </Col>
      </Row>
      <Row>
        <Col span="24">
          <div style="display: flex;justify-content: center">
            <Button @click="close">{{$t('close')}}</Button>
          </div>
        </Col>
      </Row>
    </Modal>
  </div>

</template>
<script>
  import Device from "@/api/Device";
  import MediaDevice from "@/api/MediaDevice";
  import config from '@/config'
  import {apiResult} from "@/libs/util";
  export default {
    data(){
      return{
        loading: true,
        modal:{
          show:false,
          title: "语音监听",
        },

        api: new Device(),
        protocol: 'rtc',
        playUrl: null,
        audioElement: null,
        audioPlayer: null,
        audioCtx:null,
        waveTimer:null
      }
    },
    methods:{
      play(){},
      playInit(){
        this.audioPlayer = null;
        const _this = this;
        this.audioPlayer = new ZLMRTCClient.Endpoint({
          element: this.audioElement,// video 标签
          debug: true,// 是否打印日志
          zlmsdpUrl: _this.playUrl,//流地址
          simulecast: true,
          useCamera: false,
          audioEnable: true,
          videoEnable: false,
          recvOnly: true,
        })
        console.log(">>>>>> audioPlayer:%o",this.audioPlayer);
        //协商出错
        this.audioPlayer.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR,(e)=>{// ICE 协商出错
          console.error('!!!!!!!!! ICE error: %o',e)
        });

        //播放成功
        this.audioPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_REMOTE_STREAMS,(e)=>{//获取到了远端流，可以播放
          console.log('play success: %o',e)
        });

        //交换失败
        this.audioPlayer.on(ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED,(e)=>{// offer anwser 交换失败
          console.error('!!!!!!!!!  offer anwser failed: %o',e)
        });
        //当前状态==>
        this.audioPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_CONNECTION_STATE_CHANGE,function(state)
        {// RTC 状态变化 ,详情参考 https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
          console.log('********* state: %o',state)
        });

        //rtc datachannel 打开
        this.audioPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_OPEN,function(event)
        {
          console.log('rtc datachannel open: %o',event)
        });

        //rtc datachannel 消息
        this.audioPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_MSG,function(event)
        {
          console.log('rtc datachannel mesage :',event.data)
          document.getElementById('msgrecv').value = event.data
        });
        //rtc datachannel 错误
        this.audioPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_ERR,function(event)
        {
          console.log('rtc datachannel error :',event)
        });
        //rtc datachannel 关闭
        this.audioPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_CLOSE,function(event)
        {
          console.log('rtc datachannel close :',event)
        });
      },
      close(){
        this.stop();
        this.modal.show = false;
        this.loading = true;
      },
      stop(){
        console.log(">>>>>> RtcAudioPlayer::stop:audioPlayer=%o",this.audioPlayer);
        if(!!this.audioPlayer)
        {
          this.audioPlayer.close();
          this.audioPlayer = null;
          this.audioElement = this.$refs.audioPlayer1;
          if(!!this.audioElement)
          {
            this.audioElement.srcObject = null;
            this.audioElement.load();
          }
        }
        this.MediaStreamTrack && this.MediaStreamTrack.stop();
        if (!!this.audioCtx){
          this.audioCtx.close();
          this.audioCtx=null;
        }

        if (!!this.waveTimer){
          clearInterval(this.waveTimer)
          this.waveTimer=null;
        }

      },
      openDialog(deviceId,channelId){
        //console.log(window.location.protocol + "//" + window.location.host);
        //const docUrl = new URL("http://192.168.0.129:8080/index/api/webrtc?app=live&stream=44010200492000000020_44030000492000000020&type=push");
        //console.log(docUrl);
        //console.log(config.pushUrl);
        this.modal.show = true;
        new MediaDevice().getDevices((res)=>{
          //console.log(res);
          if (!!res.errMsg){
            this.$Message.error(res.errMsg);
          }else{
            this.stop();
            this.deviceId = deviceId;
            this.channelId = channelId;
            this.getPlayUrl().then(()=>{
              this.play();
            })
          }
        })

      },
      getPlayUrl(){
        return new Promise((resolve, reject) => {
          this.api.playStart(this.deviceId,this.channelId).then(res=> {
            apiResult(res.data,false,result=>{
              if (!!result.data[this.protocol]) {
                const playUrl = result.data[this.protocol];
                //const originUrl = new URL(playUrl);
                this.playUrl = this.api.getPlayUrl(playUrl);
                this.playInit();

                //生产环境和开发不一样
/*                if (process.env.NODE_ENV === "production") {
                  //生产环境,通过nginx代理，本地IP:port+/mcpro/webrtc/
                  const docUrl = new URL(document.location);
                  let originUrl = docUrl.protocol + "//" + docUrl.hostname
                  if (!!docUrl.port){
                    originUrl = originUrl + ":" + docUrl.port;
                  }
                  originUrl = originUrl + "/mcpro/webrtc";
                  this.mediaHost = originUrl;
                  originUrl = originUrl + playUrl.substring(playUrl.indexOf("/index/api/webrtc?"));
                  console.log(">>>>>> production env play url：%o",originUrl);
                  this.playUrl = originUrl;
                  this.playInit();
                }else{
                  //开发环境
                  this.playUrl=playUrl.replace(":443/", ":8443/")
                  console.log(">>>>>> dev env play url：%o",this.playUrl);

                  this.playInit();
                }*/
                resolve()
              }
            });
            /*if (res.data.code === 0) {
              if (!!res.data.data[this.protocol]) {
                const playUrl = res.data.data[this.protocol];
                //生产环境和开发不一样
                if (process.env.NODE_ENV === "production") {
                  //生产环境,通过nginx代理，本地IP:port+/mcpro/webrtc/
                  const docUrl = new URL(document.location);
                  let originUrl = docUrl.protocol + "//" + docUrl.hostname
                  if (!!docUrl.port){
                    originUrl = originUrl + ":" + docUrl.port;
                  }
                  originUrl = originUrl + "/mcpro/webrtc";
                  this.mediaHost = originUrl;
                  originUrl = originUrl + playUrl.substring(playUrl.indexOf("/index/api/webrtc?"));
                  console.log(">>>>>> 生产环境 播放地址：%o",originUrl);
                  this.playUrl = originUrl;
                  this.playInit();
                }else{
                  //开发环境
                  this.playUrl=playUrl.replace(":443/", ":8443/")
                  console.log(">>>>>> 开发环境 播放地址：%o",this.playUrl);
                  this.playInit();
                }
                resolve()
              }
            }else{
              console.log("!!!!!!!!!错误：%o",res.data.msg);
              console.log("!!!!!!!!!获取播放地址错误，请确认设备是否在线");
            }*/
          }).catch(err => {
            reject(err)
          })
        });
      },
    },
    mounted() {
      this.modal.title = this.$t('voice_monitoring')

      const isHttps = 'https:' === document.location.protocol;
      this.protocol = isHttps?"rtcs":"rtc";
      const _this=this;
      this.$nextTick(()=>{
        _this.audioElement = _this.$refs.audioPlayer1;
        _this.audioElement.addEventListener("loadedmetadata", (res)=> {
          //关闭 MIC使用
          const mediaStream = _this.audioElement.srcObject;
          _this.MediaStreamTrack=typeof mediaStream.stop==='function'?mediaStream:mediaStream.getTracks()[0];
          //画音频波形
          new MediaDevice().audioWave(mediaStream,_this.$refs.audioCanvas,
            (res)=>{
              console.log(res);
              _this.loading = false;
              _this.audioCtx = res.audioCtx;
              _this.waveTimer = res.timer;
            })
        })
      });



    },
    beforeDestroy(){
      this.MediaStreamTrack && this.MediaStreamTrack.stop();
    },
  }
</script>
<style>
.audioPlayerJt{
  width: 100%;
  height: 30px;
  background-color: #0c0c0c;
}
</style>
